<template>
  <div class="mySearch-wrap">
    <el-form :inline="true" :model="formData" class="demo-form-inline" ref="elFormRef">
      <template v-for="item in optionItemList" :key="item.name">
        <el-form-item :label="item.title">
          <el-input
            v-if="item.type == 'text'"
            v-model="formData[item.name]"
            :placeholder="item.hidePlaceholder ? '' : '请输入' + item.title"
            :clearable="!item.hideClear"
          />
          <el-select
            v-else-if="item.type == 'select'"
            v-model="formData[item.name]"
            :placeholder="item.hidePlaceholder ? '' : '请选择' + item.title"
            :clearable="!item.hideClear"
          >
            <el-option
              v-for="it in item.selectOption.itemList"
              :key="it.value"
              :label="it.title"
              :value="it.value"
            />
          </el-select>
        </el-form-item>
      </template>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
        <template v-for="item in btnList" :key="item.title">
          <el-button
            v-if="!item.hide"
            :disabled="item.disabled"
            type="primary"
            @click="btnClick(item)"
          >
            {{ item.title }}
          </el-button>
        </template>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, type PropType } from 'vue'
import type { SearchOptionType, SearchOptionItemType, SearchOptionBtnType } from './mySearchTypes'

const props = defineProps({
  options: {
    type: Object as PropType<SearchOptionType>,
    default: () => {
      return {}
    }
  }
})

const emit = defineEmits(['getSearchData'])

/** 表单每一项的配置 */
const btnList = computed<SearchOptionBtnType[]>(() => {
  return props.options.btns || []
})
/** 按钮点击事件 */
const btnClick = (data: SearchOptionBtnType) => {
  data.onClick && data.onClick()
}
/** 表单每一项的配置 */
const optionItemList = computed<SearchOptionItemType[]>(() => {
  return props.options.list || []
})

/** 数据表单 */
const formData = ref<any>({})
/** 构建表单数据 */
const setFormData = () => {
  optionItemList.value.forEach((item) => {
    formData.value[item.name] = item.value || ''
  })
}
setFormData()

/** 点击搜索获取数据 */
const onSubmit = () => {
  const obj: any = {}
  for (const key in formData.value) {
    if (
      formData.value[key] !== '' &&
      formData.value[key] !== undefined &&
      formData.value[key] !== null
    ) {
      obj[key] = formData.value[key]
    }
  }
  emit('getSearchData', obj)
}

const elFormRef = ref()
setTimeout(() => {
  console.log(1111111, elFormRef.value.$el)
}, 2000)
</script>

<style lang="less" scoped>
.mySearch-wrap {
  width: 100%;
  .el-form-item {
    margin-bottom: 10px;
  }
  .demo-form-inline .el-input {
    --el-input-width: 220px;
  }

  .demo-form-inline .el-select {
    --el-select-width: 220px;
  }
}
</style>
